<template>
  <view class="adaptive-navbar" :style="navbarStyle">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 导航栏内容 -->
    <view class="navbar-content" :style="navbarContentStyle">
      <!-- 左侧按钮区域 -->
      <view class="navbar-left" :style="leftAreaStyle">
        <!-- 胶囊类型按钮 -->
        <view 
          v-if="(showBack && showHome)"
          class="capsule-container"
          :style="capsuleContainerStyle"
        >
          <!-- 返回按钮 -->
          <view 
          v-if="showBack" 
            class="capsule-button back-button" 
            @click.stop="handleBack"
            @touchstart="onButtonTouchStart"
            @touchend="onButtonTouchEnd"
            :style="capsuleButtonStyle"
          >
             <FontIcon 
               name="icon-arrow-left-solid"
               :size="32"
               color="#ffffff"
             />
        </view>
        
          <!-- 分隔线 -->
          <view 
            v-if="showBack && showHome" 
            class="capsule-divider"
            :style="capsuleDividerStyle"
          ></view>
          
          <!-- 首页按钮 -->
        <view 
          v-if="showHome" 
            class="capsule-button home-button" 
            @click.stop="handleHome"
            @touchstart="onButtonTouchStart"
            @touchend="onButtonTouchEnd"
            :style="capsuleButtonStyle"
          >
             <FontIcon 
               name="icon-my-home"
               :size="32"
               color="#ffffff"
             />
          </view>
        </view>
        
        <!-- 分离类型按钮 -->
        <template v-else>
          <!-- 返回按钮 -->
        <view 
            v-if="showBack" 
            class="nav-button back-button" 
            @click.stop="handleBack"
            @touchstart="onButtonTouchStart"
            @touchend="onButtonTouchEnd"
            :style="separateButtonStyle"
        >
           <FontIcon 
             name="icon-arrow-left-solid"
             :size="32"
             color="#ffffff"
           />
        </view>
        
          <!-- 首页按钮 -->
          <view 
            v-if="showHome" 
            class="nav-button home-button" 
            @click.stop="handleHome"
            @touchstart="onButtonTouchStart"
            @touchend="onButtonTouchEnd"
            :style="separateButtonStyle"
          >
            <FontIcon 
              name="icon-my-home"
              :size="32"
              color="#ffffff"
            />
          </view>
        </template>
      </view>
      
      <!-- 中间标题区域 -->
      <view class="navbar-center" :style="centerAreaStyle">
        <text class="navbar-title" :style="titleStyle" v-if="title">{{ title }}</text>
      </view>
      
      <!-- 右侧按钮区域 -->
      <view class="navbar-right" :style="rightAreaStyle">
        <slot name="right"></slot>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'AdaptiveNavBar',
  props: {
    // 标题文本
    title: {
      type: String,
      default: ''
    },
    // 背景色
    backgroundColor: {
      type: String,
      default: ''
    },
    // 文字颜色
    textColor: {
      type: String,
      default: '#ffffff'
    },
    // 是否显示返回按钮
    showBack: {
      type: Boolean,
      default: true
    },
    // 是否显示首页按钮
    showHome: {
      type: Boolean,
      default: false
    },
    // 按钮样式类型：separate(分离) | capsule(胶囊)
    buttonStyle: {
      type: String,
      default: 'separate',
      validator: value => ['separate', 'capsule'].includes(value)
    },
    // 是否固定定位
    fixed: {
      type: Boolean,
      default: true
    },
    // 是否显示阴影
    showShadow: {
      type: Boolean,
      default: true
    },
    // 阴影样式（可配置，如：'0 2rpx 8rpx rgba(0, 0, 0, 0.1)'）
    shadowStyle: {
      type: String,
      default: '0 2rpx 8rpx rgba(0, 0, 0, 0.1)'
    },
    // 样式变体：default | transparent（透明无标题，仅返回按钮，与胶囊对齐）
    variant: {
      type: String,
      default: 'default',
      validator: v => ['default', 'transparent'].includes(v)
    },
  },
  data() {
    return {
      // 系统信息
      systemInfo: {},
      // 状态栏高度
      statusBarHeight: 0,
      // 导航栏高度
      navbarHeight: 44,
      // 胶囊按钮信息
      capsuleInfo: {},
      // 安全区域
      safeAreaInsets: {},
      // 业务类型
      businessType: 1
    }
  },
  computed: {
    // 是否透明模式
    isTransparent() {
      return this.variant === 'transparent'
    },
    // 两侧与屏幕边距离，取右侧胶囊与屏幕右边距作为左右统一内边距
    sidePadding() {
      const winW = this.systemInfo && this.systemInfo.windowWidth
      const capR = this.capsuleInfo && this.capsuleInfo.right
      if (winW && capR) {
        const pad = winW - capR
        return pad > 0 ? pad : 0
      }
      return 16
    },
    // 计算背景色
    computedBackgroundColor() {
      // 如果传入了自定义背景色，优先使用
      if (this.backgroundColor) {
        return this.backgroundColor
      }
      
      // 根据业务类型自动判断背景色
      if (this.businessType === 2) {
        return '#39B54A' // 目的地接待业务 - 绿色
      } else if (this.businessType === 3) {
        return '#FBBD08' // 第三类商家 - 黄色
      } else {
        return '#0081ff' // 默认研学业务 - 蓝色
      }
    },
    
    // 导航栏整体样式
    navbarStyle() {
      const style = {
        backgroundColor: this.isTransparent ? 'transparent' : this.computedBackgroundColor,
        position: this.fixed ? 'fixed' : 'relative',
        top: 0,
        left: 0,
        right: 0,
        zIndex: 999
      }
      
      if (this.showShadow && !this.isTransparent) {
        style.boxShadow = this.shadowStyle
      }
      
      return style
    },
    
    // 导航栏内容样式
    navbarContentStyle() {
      return {
        height: this.navbarHeight + 'px',
        position: 'relative',
		display: 'flex',
		alignItems: 'center',
		justifyContent: 'center'
      }
    },
    
    // 左侧区域样式
    leftAreaStyle() {
      return {
        width: this.capsuleInfo.left + 'px',
        height: this.capsuleInfo.height + 'px',
        top: (this.capsuleInfo.top - this.statusBarHeight) + 'px',
        left: this.isTransparent ? (this.sidePadding + 'px') : '40rpx'
      }
    },
    
    // 中间区域样式
    centerAreaStyle() {
      return {
        height: this.capsuleInfo.height + 'px',
        top: (this.capsuleInfo.top - this.statusBarHeight) + 'px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }
    },
    
    // 右侧区域样式
    rightAreaStyle() {
      return {
        width: this.capsuleInfo.right + 'px',
        height: this.capsuleInfo.height + 'px',
        top: (this.capsuleInfo.top - this.statusBarHeight) + 'px',
        right: '0px'
      }
    },
    
    // 分离类型按钮样式
    separateButtonStyle() {
      const sizePx = (this.capsuleInfo && this.capsuleInfo.height) ? (this.capsuleInfo.height + 'px') : '52rpx'
      return {
        width: sizePx,
        height: sizePx,
        minWidth: sizePx,
        minHeight: sizePx,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: '20rpx',
        borderRadius: '50%',
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        transition: 'all 0.3s ease',
        color: this.textColor,
        position: 'relative',
        zIndex: 10,
        cursor: 'pointer',
        userSelect: 'none',
        WebkitUserSelect: 'none',
        WebkitTapHighlightColor: 'transparent'
      }
    },
    
    // 胶囊容器样式
    capsuleContainerStyle() {
      const capsuleHeight = (this.capsuleInfo && this.capsuleInfo.height) ? this.capsuleInfo.height : 32
      const capsuleWidth = (this.capsuleInfo && this.capsuleInfo.width) ? this.capsuleInfo.width : 87
      const borderRadius = capsuleHeight / 2
      
      return {
        height: capsuleHeight + 'px',
        width: capsuleWidth + 'px',
        minHeight: capsuleHeight + 'px',
        minWidth: capsuleWidth + 'px',
        maxHeight: capsuleHeight + 'px',
        maxWidth: capsuleWidth + 'px',
        display: 'flex',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        borderRadius: borderRadius + 'px',
        padding: '0',
        position: 'relative',
        zIndex: 10,
        backdropFilter: 'blur(20rpx)',
        WebkitBackdropFilter: 'blur(20rpx)',
        border: 'none',
        boxShadow: '0 2rpx 8rpx rgba(0, 0, 0, 0.1)',
        overflow: 'hidden',
        justifyContent: 'space-between',
        boxSizing: 'border-box',
        WebkitBoxSizing: 'border-box'
      }
    },
    
    // 胶囊按钮样式
    capsuleButtonStyle() {
      const capsuleHeight = (this.capsuleInfo && this.capsuleInfo.height) ? this.capsuleInfo.height : 32
      const capsuleWidth = (this.capsuleInfo && this.capsuleInfo.width) ? this.capsuleInfo.width : 87
      const buttonWidth = capsuleWidth / 2
      const borderRadius = capsuleHeight / 2
      return {
        width: buttonWidth + 'px',
        height: '100%',
        minWidth: buttonWidth + 'px',
        minHeight: capsuleHeight + 'px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: borderRadius + 'px',
        backgroundColor: 'transparent',
        transition: 'all 0.2s ease',
        color: this.textColor,
        position: 'relative',
        cursor: 'pointer',
        userSelect: 'none',
        WebkitUserSelect: 'none',
        WebkitTapHighlightColor: 'transparent',
        flexShrink: 0
      }
    },
    
    // 胶囊分隔线样式
    capsuleDividerStyle() {
      const capsuleHeight = (this.capsuleInfo && this.capsuleInfo.height) ? this.capsuleInfo.height : 32
      const capsuleWidth = (this.capsuleInfo && this.capsuleInfo.width) ? this.capsuleInfo.width : 87
      const dividerHeight = capsuleHeight * 0.6
      return {
        width: '1rpx',
        height: dividerHeight + 'px',
        backgroundColor: this.textColor + '20',
        position: 'absolute',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        borderRadius: '0.5rpx',
        pointerEvents: 'none'
      }
    },
    
    
    // 标题样式
    titleStyle() {
      return {
        color: this.textColor,
        fontSize: '32rpx',
        fontWeight: '500',
        textAlign: 'center',
        maxWidth: '100%',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }
    }
  },
  mounted() {
    this.initSystemInfo()
    this.loadBusinessTypeFromCache()
    this.saveNavbarHeightToCache()
    console.log('AdaptiveNavBar mounted, title:', this.title, 'businessType:', this.businessType, 'buttonStyle:', this.buttonStyle)
  },
  watch: {
    title(newVal) {
      console.log('Title changed to:', newVal)
    },
    buttonStyle(newVal, oldVal) {
      console.log('ButtonStyle changed from', oldVal, 'to', newVal)
    }
  },
  methods: {
    // 初始化系统信息
    initSystemInfo() {
      try {
      // 获取系统信息
        this.systemInfo = uni.getSystemInfoSync()
        
        // 设置状态栏高度
        this.statusBarHeight = this.systemInfo.statusBarHeight || 0
      
      // 获取胶囊按钮信息
        this.capsuleInfo = uni.getMenuButtonBoundingClientRect()
        console.log('胶囊按钮信息:', this.capsuleInfo)
        
        // 计算导航栏高度
        this.calculateNavbarHeight()
        
        // 获取安全区域信息
        this.safeAreaInsets = this.systemInfo.safeAreaInsets || {}
        
      } catch (error) {
        console.error('获取系统信息失败:', error)
        // 设置默认值
        this.statusBarHeight = 20
        this.capsuleInfo = {
          left: 10,
          right: 10,
          top: 10,
          bottom: 10,
          width: 87,
          height: 32
        }
      }
    },
    
    // 计算导航栏高度
    calculateNavbarHeight() {
      if (this.capsuleInfo && this.capsuleInfo.height) {
        // 胶囊按钮高度 + 上下间距
        this.navbarHeight = this.capsuleInfo.height + (this.capsuleInfo.top - this.statusBarHeight) * 2
      } else {
        // 默认高度
        this.navbarHeight = 44
      }
    },
    
    // 处理返回按钮点击
    handleBack() {
      console.log('返回按钮被点击')
      
      // 触发自定义事件，让父组件可以监听
      this.$emit('back')
      
      // 组件内部处理返回逻辑
      const pages = getCurrentPages()
      if (pages.length > 1) {
        // 有上一页，执行返回
        uni.navigateBack({
          delta: 1
        })
      } else {
        // 没有上一页，跳转到首页
        uni.reLaunch({
          url: '/pages/customer/index/index'
        })
      }
    },
    
    // 处理首页按钮点击
    handleHome() {
      console.log('首页按钮被点击')
      
      // 触发自定义事件，让父组件可以监听
      this.$emit('home')
      
      // 组件内部处理首页跳转逻辑
      uni.reLaunch({
        url: '/pages/customer/index/index'
      })
    },
    
    // 按钮触摸开始
    onButtonTouchStart(e) {
      console.log('按钮触摸开始', e)
      // 添加触摸反馈
      e.currentTarget.style.transform = 'scale(0.95)'
      if (!this.isTransparent) {
        e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.2)'
      }
    },
    
    // 按钮触摸结束
    onButtonTouchEnd(e) {
      console.log('按钮触摸结束', e)
      // 恢复按钮状态
      e.currentTarget.style.transform = 'scale(1)'
      if (!this.isTransparent) {
        e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.1)'
      } else {
        e.currentTarget.style.backgroundColor = 'transparent'
      }
    },
    
    // 保存导航栏高度到缓存
    saveNavbarHeightToCache() {
      try {
        const navbarHeightData = {
          totalHeight: this.statusBarHeight + this.navbarHeight, // 总高度 = 状态栏高度 + 导航栏高度
          statusBarHeight: this.statusBarHeight,
          navbarHeight: this.navbarHeight,
          capsuleHeight: this.capsuleInfo.height || 32,
          timestamp: Date.now()
        }
        
        uni.setStorageSync('navbarHeight', navbarHeightData)
        console.log('导航栏高度已保存到缓存:', navbarHeightData)
      } catch (error) {
        console.error('保存导航栏高度到缓存失败:', error)
      }
    },
    
    // 获取缓存的导航栏高度
    getCachedNavbarHeight() {
      try {
        const cachedData = uni.getStorageSync('navbarHeight')
        if (cachedData && cachedData.timestamp) {
          // 检查缓存是否过期（24小时）
          const isExpired = Date.now() - cachedData.timestamp > 24 * 60 * 60 * 1000
          if (!isExpired) {
            return cachedData
          }
        }
        return null
      } catch (error) {
        console.error('获取缓存的导航栏高度失败:', error)
        return null
      }
    },
    
    // 从缓存中读取业务类型
    loadBusinessTypeFromCache() {
      try {
        const companyInfo = uni.getStorageSync('companyInfo')
        if (companyInfo && companyInfo.businessType) {
          const bt = Number(companyInfo.businessType)
          this.businessType = Number.isNaN(bt) ? companyInfo.businessType : bt
          console.log('从缓存读取到businessType:', this.businessType)
        } else {
          console.log('缓存中未找到companyInfo.businessType，使用默认值:', this.businessType)
        }
      } catch (error) {
        console.error('读取companyInfo失败:', error)
        console.log('使用默认businessType:', this.businessType)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.adaptive-navbar {
  width: 100%;
  background-color: #ff6700;

.status-bar {
  width: 100%;
  background-color: inherit;
}

.navbar-content {
    width: 100%;
  position: relative;

    .navbar-left {
      position: absolute;
      z-index: 10;
  display: flex;
  align-items: center;

.nav-button {
  cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        z-index: 11;
        user-select: none;
        -webkit-user-select: none;
        -webkit-tap-highlight-color: transparent;
        
        &:active {
          transform: scale(0.95);
          background-color: rgba(255, 255, 255, 0.2);
        }
  
  &:hover {
          background-color: rgba(255, 255, 255, 0.15);
  }
  
        .nav-icon {
          transition: all 0.3s ease;
          pointer-events: none;
        }
      }
      
      // 胶囊容器样式
      .capsule-container {
        cursor: pointer;
        transition: all 0.2s ease;
        position: relative;
        z-index: 11;
        user-select: none;
        -webkit-user-select: none;
        -webkit-tap-highlight-color: transparent;
        
        &:active {
          transform: scale(0.96);
          background-color: rgba(255, 255, 255, 0.9);
          box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.15);
        }
        
        &:hover {
          background-color: rgba(255, 255, 255, 0.85);
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.12);
        }
        
        // 胶囊按钮样式
        .capsule-button {
          cursor: pointer;
  transition: all 0.2s ease;
          position: relative;
          user-select: none;
          -webkit-user-select: none;
          -webkit-tap-highlight-color: transparent;
          
          &:active {
            transform: scale(0.88);
            background-color: rgba(0, 0, 0, 0.05);
          }
          
          &:hover {
            background-color: rgba(0, 0, 0, 0.03);
          }
          
  .nav-icon {
            transition: all 0.2s ease;
            pointer-events: none;
  }
}

        // 胶囊分隔线样式
        .capsule-divider {
          transition: all 0.2s ease;
        }
      }
    }
    
    .navbar-center {
      position: absolute;
      z-index: 3;
      
      .navbar-title {
        width: 100%;
        height: 100%;
        line-height: 1;
        text-align: center;
      }
    }
    
    .navbar-right {
      position: absolute;
      z-index: 2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
  }
}
}

// 适配不同屏幕尺寸
@media screen and (max-width: 320px) {
  .adaptive-navbar {
    .navbar-content {
      .navbar-left {
        .nav-button {
          width: 50rpx;
          height: 50rpx;
          margin-right: 15rpx;
          
  .nav-icon {
            width: 28rpx;
            height: 28rpx;
          }
  }
}

.navbar-center {
  .navbar-title {
    font-size: 28rpx;
  }
      }
    }
  }
}

@media screen and (min-width: 414px) {
  .adaptive-navbar {
    .navbar-content {
      .navbar-left {
        .nav-button {
          width: 70rpx;
          height: 70rpx;
          margin-right: 25rpx;
          
          .nav-icon {
            width: 36rpx;
            height: 36rpx;
          }
        }
      }
      
      .navbar-center {
  .navbar-title {
    font-size: 36rpx;
  }
      }
    }
  }
}

// 适配横屏
@media screen and (orientation: landscape) {
  .adaptive-navbar {
    .navbar-content {
      .navbar-left {
        .nav-button {
          width: 50rpx;
          height: 50rpx;
  
  .nav-icon {
            width: 28rpx;
            height: 28rpx;
          }
        }
      }
      
      .navbar-center {
        .navbar-title {
          font-size: 28rpx;
        }
      }
    }
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  .adaptive-navbar {
    .navbar-content {
      .navbar-left {
  .nav-button {
          background-color: rgba(255, 255, 255, 0.15);
    
    &:active {
            background-color: rgba(255, 255, 255, 0.25);
          }
        }
      }
    }
  }
}
</style>
